package eg.backend.base.repository;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;

public class EntityRepositoryImpl<T, PK extends Serializable>  implements EntityRepository<T, PK> {
	protected Class<T> type;
	protected BaseDao baseDao;

	@SuppressWarnings("unchecked")
	@PostConstruct
	public void init() {
		if (type == null) {
			type = (Class<T>) GenericsUtils.getGenericClass(this.getClass());
		}
	}

	@Autowired
	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

	public void setType(Class<T> type) {
		this.type = type;
	}
	
	public T save(T entity) {
		return baseDao.save(entity);
	}

	public void delete(T entity) {
		baseDao.delete(entity);
	}

	public void delete(PK identifier) {
		this.delete(this.get(identifier));
	}

	public void deleteAll(List<T> entities) {
		for (T entity : entities) {
			delete(entity);
		}
	}

	public T get(PK identifier) {
		return (T) baseDao.get(identifier, type);
	}
	
	public List<T> loadAll() {
		return baseDao.loadAll(type);
	}
	
	public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
		return baseDao.findByNamedQuery(queryName, Integer.MAX_VALUE, queryParams);
	}
	
	public T getByNamedQuery(String queryName, Map<String, Object> queryParams) {
		List<T> result = baseDao.findByNamedQuery(queryName, Integer.MAX_VALUE, queryParams);
		if(result == null || result.size() == 0)
			return null;
		return result.get(0);
	}
	
	public int update(String queryName, Map<String, Object> queryParams) {
		return baseDao.updateByNamedQuery(queryName, queryParams);
	}
}
